package org.jeecg.modules.system.service.impl;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.metadata.Sheet;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.entity.RedInformation;
import org.jeecg.modules.system.entity.RedInformationSum;
import org.jeecg.modules.system.mapper.RedInformationMapper;
import org.jeecg.modules.system.service.IRedInformationService;
import org.jeecg.modules.util.ExcelUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description: 红色信息表
 * @Author: jeecg-boot
 * @Date: 2025-04-29
 * @Version: V1.0
 */
@Service
@Slf4j
public class RedInformationServiceImpl extends ServiceImpl<RedInformationMapper, RedInformation> implements IRedInformationService {

    @Value("${jeecg.path.upload}")
    private String upLoadPath;
    @Autowired
    RedInformationMapper redInformationMapper;

    @Transactional
    @Override
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                Sheet sheet = new Sheet(1, 1);
                ExcelUtil.ExcelListener excelListener = new ExcelUtil.ExcelListener();
                EasyExcelFactory.readBySax(file.getInputStream(), sheet, excelListener);
                List<Object> objects = excelListener.getDatas();
                log.info("文件行数:{}", objects.size());
                List<RedInformation> redInformations = new ArrayList<>();

                Date date = new Date();

                for (Object o : objects) {
                    List<String> list = (ArrayList) o;
                    log.info("处理中{}，{}",list.get(2),list.size());
                    if(list.size()<=11){
                        continue;
                    }
                    if (list.get(11)!=null&&StringUtils.isNotBlank(list.get(11))) {
                        RedInformation redInformation = new RedInformation();
                        redInformation.setSupplier(list.get(2));
                        redInformation.setInfoId(list.get(3));
                        redInformation.setTaxFreeAmount(list.get(5));
                        redInformation.setTaxAmount(list.get(6));

                        // 1. 移除百分号并解析为double
                        String numberPart = list.get(7).replace("%", "");
                        double value = Double.parseDouble(numberPart);

                        // 2. 四舍五入到最近的整数
                        int roundedValue = (int) Math.round(value);

                        // 3. 拼接百分号并返回
                        redInformation.setRate(roundedValue + "%");
                        redInformation.setSubSettlement(list.get(11));
                        redInformation.setTotalTaxPrice(list.get(8));
                        redInformations.add(redInformation);

                    }

                }
                redInformationMapper.deleteAll();
                this.saveBatch(redInformations);
                return Result.ok("文件导入成功!");
            } catch (Exception e) {
                //update-begin-author:taoyan date:20211124 for: 导入数据重复增加提示
                String msg = e.getMessage();
                log.error(msg, e);
                if (msg != null && msg.indexOf("Duplicate entry") >= 0) {
                    return Result.error("文件导入失败:有重复数据！");
                } else {
                    return Result.error("文件导入失败:" + e.getMessage());
                }
                //update-end-author:taoyan date:20211124 for: 导入数据重复增加提示
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    @Override
    public ModelAndView exportXls(HttpServletRequest request, String title) {
        // Step.1 组装查询条件
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Step.2 获取导出数据
        List<RedInformationSum> exportList = redInformationMapper.selectSumInfo();

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.FILE_NAME, title);
        mv.addObject(NormalExcelConstants.CLASS, RedInformationSum.class);
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams = new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title);
        exportParams.setImageBasePath(upLoadPath);
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }
}
